
package com.lzb.musicplayer.utils;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;


import com.lzb.musicplayer.bean.MusicFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MusicScannerUtil {

    public void loadMusicFiles(Activity activity,OnCallBackListener onCallBackListener) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Handler handler = new Handler(Looper.getMainLooper());

        executor.execute(() -> {
            List<MusicFile> musicFiles = new ArrayList<>();
            Set<String> directories = new HashSet<>();

            // 修正后的projection数组
            String[] projection = {
                    MediaStore.Audio.Media.DATA,
                    MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media.ARTIST,
                    MediaStore.Audio.Media.ALBUM,
                    MediaStore.Audio.Media.DURATION,
                    MediaStore.Audio.Media.ALBUM_ID
            }; // 移除了GENRE列

            String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

            try (Cursor cursor = activity.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    projection,
                    selection,
                    null,
                    null)) {

                if (cursor != null) {
                    int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                    int titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
                    int artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
                    int albumColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
                    int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION);
                    int albumIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);


                    while (cursor.moveToNext()) {
                        MusicFile musicFile = new MusicFile();
                        String path = cursor.getString(dataColumn);
                        musicFile.setPath(path);
                        musicFile.setTitle(cursor.getString(titleColumn));
                        if (!TextUtils.isEmpty(cursor.getString(artistColumn))&&!"<unknown>".equals(cursor.getString(artistColumn))){
                            musicFile.setArtist(cursor.getString(artistColumn));
                        }else {
                            musicFile.setArtist("未知艺术家");
                        }

                        musicFile.setAlbum(cursor.getString(albumColumn));
                        musicFile.setDuration(cursor.getLong(durationColumn));

                        // 使用MediaMetadataRetriever获取流派信息
                        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                        try {
                            retriever.setDataSource(path);
                            // 正确获取流派的方式
                            String genre = retriever.extractMetadata(
                                    MediaMetadataRetriever.METADATA_KEY_GENRE);
                            musicFile.setGenre(genre);
                        } catch (Exception e) {
                            musicFile.setGenre("");
                            e.printStackTrace();
                        } finally {
                            try {
                                retriever.release();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        // 获取专辑封面
                        long albumId = cursor.getLong(albumIdColumn);
                        long artistColumnId = cursor.getLong(artistColumn);

                      //  Bitmap albumCover = getAlbumArt(activity,albumId);
                        Bitmap albumCover = getArtistImage(activity,artistColumnId);
                        musicFile.setAlbumCover(albumId);
                        musicFile.setArtistCover(artistColumnId);


                        musicFiles.add(musicFile);
                        directories.add(new File(path).getParent());
                    }
                }
            }

            List<String> directoryList = new ArrayList<>(directories);

            handler.post(() -> {
                // 更新UI，directoryList包含所有有音乐的目录
                // musicFiles包含所有音乐文件信息
                int size = directoryList.size();
                int size1 = musicFiles.size();
                if (onCallBackListener!=null){
                    onCallBackListener.onCallBack(musicFiles);
                }
            });
        });
    }

    public static Bitmap getAlbumArt(Context activity, long albumId) {
        Uri albumArtUri = ContentUris.withAppendedId(
                Uri.parse("content://media/external/audio/albumart"), albumId);

        try (InputStream inputStream = activity.getContentResolver().openInputStream(albumArtUri)) {
            return BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            return null;
        }
    }

    public static Bitmap getArtistImage(Activity context, long artistId) {
        Uri artistUri = Uri.parse("content://media/external/audio/artists/" + artistId + "/albums/");
        String[] projection = { MediaStore.Audio.Albums.ALBUM_ART }; // 获取专辑封面
        Cursor cursor = context.getContentResolver().query(artistUri, projection, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    int albumArtColumn = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
                    byte[] albumArt = cursor.getBlob(albumArtColumn);
                    if (albumArt != null) {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(albumArt, 0, albumArt.length);
                        return bitmap;
                    }
                }
            } finally {
                cursor.close();
            }
        } else {
            // 处理没有找到艺术家的情况，例如设置默认图片等。
          return null;
        }
        return null;
    }
    public interface OnCallBackListener{
        void onCallBack(List<MusicFile> list);
    }
}